package com.mopa.renren;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.TreeSet;
import com.mopa.http.Callback;
import com.mopa.http.RenRenAPI;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
//import com.tencent.tauth.http.TDebug;
public class UploadPicClickListener implements OnClickListener {
	private RenShareActivity mActivity;
	public UploadPicClickListener(RenShareActivity activity) {
		mActivity = activity;
	}
	@Override
	public void onClick(View v) {
		if (!mActivity.satisfyConditions()) {
			return;
		}
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		mActivity.startActivityForResult(intent, RenShareActivity.REQUEST_PICK_PICTURE);
		
	}
	public static void uploadPic(final RenShareActivity activity, Uri uri) {
		activity.showDialog(RenShareActivity.PROGRESS);
		Bundle params = new Bundle();
		byte[] buff = null;
		try {
			InputStream is = activity.getContentResolver().openInputStream(uri);
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while( (len = is.read(buffer)) !=-1 ){
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			is.close();
			buff = outSteam.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		params.putString("method", "photos.upload");
		params.putString("v", "1.0");
		params.putString("access_token", activity.mAccessToken);
		params.putString("format", "json");//
		params.putString("caption", "mopa_" + System.currentTimeMillis() + ".png");
		StringBuffer sb = new StringBuffer();
		Set<String> keys = new TreeSet<String>(params.keySet());
		for (String key : keys) {
			sb.append(key);
			sb.append("=");
			sb.append(params.getString(key));
		}
		sb.append(RenRenItem.SECRET_KEY);
		params.putString("sig",WUtils.md5(sb.toString()));
		params.putByteArray("picture.png", buff);//图片二进制
		RenRenAPI.uploadPic(params, new Callback() {
			
			@Override
			public void onSuccess(final Object obj) {
				// TODO Auto-generated method stub
                 activity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						activity.dismissDialog(RenShareActivity.PROGRESS);
						activity.showMessage("用户上传照片返回数据", obj.toString());
					}
				});
			}
			
			@Override
			public void onFail(final int ret, final String msg) {
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						activity.dismissDialog(RenShareActivity.PROGRESS);
						activity.showMessage("用户上传照片返回数据", "ret:"+ret+"msg:"+msg);
					}
				});
				
			}
		});
	}

}
